


import { engine } from "../../engine/engine";
import { WebDB } from "../webdb/WebDB";
export class WebDBMgr {
    static dbMap: { [key: string]: WebDB } = {}
    static getDB(dbName: string) {
        let db = this.dbMap[dbName]
        if (!db) {
            db = new WebDB(dbName);
            this.dbMap[dbName] = db;
        }
        // console.log('getDB ok', db)
        return db;
    }

    static execData(dbName: string, sqlStr: string): Promise<any> {
        engine.log(' dbName ', dbName, sqlStr)
        return new Promise((reslove: Function, reject: Function) => {
            var db = this.getDB(dbName)
            try {
                db.exec(sqlStr);
                reslove('')
            } catch (error) {
                // console.log(error);
                reslove(error)
            }
        })
    }

    static setData(dbName: string, sqlStr: string, ...data: any): Promise<any> {
        return new Promise((reslove: Function, reject: Function) => {
            try {
                var db = this.getDB(dbName)
                var stmt = db.prepare(sqlStr);
                stmt.run(...data);
                reslove('')
            } catch (error) {
                reslove(error)
            }

        })
    }

    static getData(dbName: string, sqlStr: string, ...data: any): Promise<any> {
        return new Promise((reslove: Function, reject: Function) => {
            try {
                var db = this.getDB(dbName)
                var stmt = db.prepare(sqlStr);
                var row = stmt.get(data);
                reslove(row)
            } catch (error) {
                reslove(null)
            }

        })

    }

    static allData(dbName: string, sqlStr: string, ...data: any): Promise<any> {
        return new Promise((reslove: Function, reject: Function) => {
            try {
                var db = this.getDB(dbName)
                var stmt = db.prepare(sqlStr);
                var row = stmt.all(data);
                reslove(row)
            } catch (error) {
                reslove(null)
            }

        })

    }

    static transactionData(dbName: string, sqlStr: string, list: any[]) {
        engine.warn(' sqlStr ', sqlStr, list)
        return new Promise((reslove: Function, reject: Function) => {
            try {
                var db = this.getDB(dbName)

                const stmt = db.prepare(sqlStr);

                const transactionMany = db.transaction((params) => {
                    for (const p of params) stmt.run(p);
                });
                // LogUtils.log(' list ', list)
                transactionMany(list);
                reslove('');
            } catch (error) {
                engine.log(' error ', error)
                reslove(error);
            }

        })

    }
}